package com.scrcu.cloud.wechat.home.endpoint.common.utils;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisWorker {

    private static final long BEGIN_TIMESTAMP = 1672531200;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private static final int COUNT_BIT = 32;

    public long generateId(String keyPrefix){
        //生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond-BEGIN_TIMESTAMP;

        //生成序列号
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd")); //方便统计
        System.out.println(date);
        long count = stringRedisTemplate.opsForValue().increment("icr:"+keyPrefix+":"+date);
        System.out.println(count);
        //拼接并且返回
        return timestamp << COUNT_BIT | count;
        //位运算： 先左移 timestamp 然后再用 或运算补齐count
        //11055524992808245
    }

    public static void main(String[] args) {
        LocalDateTime time = LocalDateTime.of(2023,1,1,0,0,0);
        long second = time.toEpochSecond(ZoneOffset.UTC);  //1672531200
        System.out.println(second);

//        System.out.println(new RedisWorker().generateId("order"));
    }
}
